package com.eam.eventhandler;

import com.eam.data.EamFacilitiesMaintain;
import org.hibernate.Query;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.base.model.Property;
import org.openbravo.client.kernel.event.EntityDeleteEvent;
import org.openbravo.client.kernel.event.EntityNewEvent;
import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
import org.openbravo.client.kernel.event.EntityUpdateEvent;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.database.SessionInfo;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.service.db.DalConnectionProvider;
import javax.enterprise.event.Observes;

public class FacilityMaintEventHandler extends EntityPersistenceEventObserver {
	private static Entity[] entities = { ModelProvider.getInstance().getEntity(EamFacilitiesMaintain.ENTITY_NAME) };

	@Override
	protected Entity[] getObservedEntities() {
		return entities;
	}

	public void onUpdate(@Observes EntityUpdateEvent event) throws Throwable {
		if (!isValidEvent(event)) {
			return;
		}

		boolean outcome = true;
		boolean outcomes = true;
		// 获取项目
		EamFacilitiesMaintain details = (EamFacilitiesMaintain) event.getTargetInstance();
		
		EamFacilitiesMaintain old_item = null;

		
		// 获取维保项目ID
		String m_id = details.getEamMaintainItem().getId();
		//获取设备ID
		String groupId = details.getEamModelGroup().getId();
		//获取计划负责人
		String planuser = details.getPlanUser();
		//获取参与人员
		String groupuser = details.getGroupUser();
		
		//判断参与人员是否都在用户管理存在
		
		if(groupuser != null){
			String [] Groupmembers = groupuser.split(",");
			
			int numbers = Groupmembers.length;
			
			for(int i = 0; i<numbers ; i++){
				String name = Groupmembers[i]; 
				
				String eql = "select m from ADUser m where m.name = :plan_user";
				Query results = OBDal.getInstance().getSession().createQuery(eql);
				results.setString("plan_user", name);
				
				if(results.list().size() <= 0){
					outcome = false;
				}
				
			}
		}
		
		if(planuser != null){
			//判断计划负责人是否在用户管理（AD_USER）里存在
			String qql = "select m from ADUser m where m.name = :plan_user";
			Query results = OBDal.getInstance().getSession().createQuery(qql);
			results.setString("plan_user", planuser);
			
			if(results.list().size() <= 0){
				outcomes = false;
			}
		}
		
		
		
		
		String hql = "select efm from " + EamFacilitiesMaintain.ENTITY_NAME + " efm where efm.emesMaintain.id =:m_id and efm.eamModelGroup.id =:groupId ";
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("m_id", m_id);
		query.setString("groupId", groupId);
		old_item = (EamFacilitiesMaintain) query.uniqueResult();
		
		if(query.list().size() > 1){
			String language = OBContext.getOBContext().getLanguage().getLanguage();
			ConnectionProvider conn = new DalConnectionProvider(false);
			throw new OBException(Utility.messageBD(conn, details.getEamMaintainItem().getName()+"已经存在，请仔细检查。", language));
		}
		
		if(!outcome){
			String language = OBContext.getOBContext().getLanguage().getLanguage();
			ConnectionProvider conn = new DalConnectionProvider(false);
			throw new OBException(Utility.messageBD(conn, "参与人员中有人不在用户管理里，请仔细检查！。", language));
		}
		
		if(!outcomes){
			String language = OBContext.getOBContext().getLanguage().getLanguage();
			ConnectionProvider conn = new DalConnectionProvider(false);
			throw new OBException(Utility.messageBD(conn, "计划负责人"+planuser+"不在用户管理里，请仔细检查！。", language));
		}
		

	}

	public void onSave(@Observes EntityNewEvent event) {
		if (!isValidEvent(event)) {
			return;
		}

		String tabId = SessionInfo.getProcessId();

		if (tabId == null) {
			return;
		}
		
		boolean outcome = true;
		boolean outcomes = true;
		// 获取项目
		EamFacilitiesMaintain details = (EamFacilitiesMaintain) event.getTargetInstance();
		
		EamFacilitiesMaintain old_item = null;

		
		// 获取维保项目ID
		String m_id = details.getEamMaintainItem().getId();
		//获取设备ID
		String groupId = details.getEamModelGroup().getId();
		
//		//获取计划负责人
//		String planuser = details.getEamMaintainItem().getPlanUser();
//		//获取参与人员
//		String groupuser = details.getEamMaintainItem().getGroupUser();
//		//获取常规保养周期
//		String Maintenancecycle = details.getEamMaintainItem().getPlanType();
		
		
		// 将要更改的实体类
		final Entity detailsEntity = ModelProvider.getInstance().getEntity(EamFacilitiesMaintain.ENTITY_NAME);
		//将计划负责人存入项目表中
		final Property planusername = detailsEntity.getProperty(EamFacilitiesMaintain.PROPERTY_PLANUSER);
		//将参与人员存入项目表中
		final Property groupusername = detailsEntity.getProperty(EamFacilitiesMaintain.PROPERTY_GROUPUSER);
		//将保养周期存入项目表中
		final Property cycle = detailsEntity.getProperty(EamFacilitiesMaintain.PROPERTY_PLANTYPE);
	

		//判断参与人员是否都在用户管理存在
//		if(groupuser != null){
//			String [] Groupmembers = groupuser.split(",");
//			int numbers = Groupmembers.length;
//
//			for(int i = 0; i<numbers ; i++){
//				String name = Groupmembers[i];
//
//				String eql = "select m from ADUser m where m.name = :plan_user";
//				Query results = OBDal.getInstance().getSession().createQuery(eql);
//				results.setString("plan_user", name);
//
//				if(results.list().size() <= 0){
//					outcome = false;
//				}
//
//			}
//		}
//
//		if(planuser != null){
//			//判断计划负责人是否在用户管理（AD_USER）里存在
//			String qql = "select m from ADUser m where m.name = :plan_user";
//			Query results = OBDal.getInstance().getSession().createQuery(qql);
//			results.setString("plan_user", planuser);
//
//			if(results.list().size() <= 0){
//				outcomes = false;
//			}
//		}
//		event.setCurrentState(cycle, Maintenancecycle);
		
		String hql = "select efm from " + EamFacilitiesMaintain.ENTITY_NAME + " efm where efm.emesMaintain.id =:m_id and efm.eamModelGroup.id =:groupId ";
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("m_id", m_id);
		query.setString("groupId", groupId);
		old_item = (EamFacilitiesMaintain) query.uniqueResult();
		
		if(old_item != null){
			String language = OBContext.getOBContext().getLanguage().getLanguage();
			ConnectionProvider conn = new DalConnectionProvider(false);
			throw new OBException(Utility.messageBD(conn, details.getEamMaintainItem().getName()+"已经存在，请仔细检查。", language));
		}
		
//		if(!outcome){
//			String language = OBContext.getOBContext().getLanguage().getLanguage();
//			ConnectionProvider conn = new DalConnectionProvider(false);
//			throw new OBException(Utility.messageBD(conn, "保养项目的参与人员中有人不在用户管理里，请仔细检查！。", language));
//		}else{
//			event.setCurrentState(groupusername, groupuser);
//		}
		
//		if(!outcomes){
//			String language = OBContext.getOBContext().getLanguage().getLanguage();
//			ConnectionProvider conn = new DalConnectionProvider(false);
//			throw new OBException(Utility.messageBD(conn, "保养项目的计划负责人"+planuser+"不在用户管理里，请仔细检查！。", language));
//		}else{
//			event.setCurrentState(planusername, planuser);
//		}
	}

	public void onDelete(@Observes EntityDeleteEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
	}

}
